﻿using System;
using System.IO;
using System.Text;
using System.Windows;
using FileClient.Core.Configuration;
using FileClient.Wpf.Configuration;
using FileClient.Wpf.Validation;
using Newtonsoft.Json;

namespace FileClient.Wpf;

public partial class ConfigPopupWindow : Window
{
    public FileServerOption ViewModel { get; set; }
    
    private readonly string _appSettingConfig;

    public ConfigPopupWindow(string appSettingConfig)
    {
        ViewModel = new FileServerOption();
        _appSettingConfig = appSettingConfig;
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = this;
    }

    public bool IsSetting { get; private set; }

    private void BtnConfigConfirm_OnClick(object sender, RoutedEventArgs e)
    {
        try
        {
            ViewModel.CheckDataAnnotations().CheckValidResult();
            using var stream = new FileStream(_appSettingConfig, FileMode.OpenOrCreate);
            var clientSetting = new ClientSetting()
            {
                FileServerSetting = ViewModel
            };
            var configLine = JsonConvert.SerializeObject(clientSetting);
            stream.Write(Encoding.Default.GetBytes(configLine));
            IsSetting = true;
            Close();
        }
        catch (Exception exception)
        {
            MessageBox.Show($"失败配置失败,原因:{exception.Message}", "配置", MessageBoxButton.OK, MessageBoxImage.Information);
           //this.Close();
        }
        
    }

    private void BtnConfigCancel_OnClick(object sender, RoutedEventArgs e)
    {
        this.Close();
    }
}